package com.bdqn.shiro.config.shiro;



import com.bdqn.shiro.mapper.RoleMapper;
import com.bdqn.shiro.pojo.Right;
import com.bdqn.shiro.pojo.Role;
import com.bdqn.shiro.pojo.SysRight;
import com.bdqn.shiro.pojo.User;
import com.bdqn.shiro.service.RoleService;
import com.bdqn.shiro.service.SysRightService;
import com.bdqn.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private SysRightService sysRightService;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用 MyShiroRealm.doGetAuthenticationInfo 获取身份信息！ ");
        //获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        User user1=new User();
        user1.setUsrName(usrName);
        User user = userService.getUser(user1);
        if (user == null) {
            throw new UnknownAccountException(); //账号错误
        }
        if (user.getUsrFlag() == null || user.getUsrFlag().intValue() == 0) {
            throw new LockedAccountException(); //账号锁定
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,//身份(根据用户名查询数据库获得的用户)
                user.getUsrPassword(),//凭证(查询数据库获得的密码)getName()//Realm 对象的名称
                ByteSource.Util.bytes("czkt"),//加盐
                getName()//Realm 对象的名称
        );
        //返回身份信
        System.out.println(info.toString());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用 MyShiroRealm.doGetAuthorizationInfo 获取权限信息！ ");
        //获得权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        System.out.println(user.toString());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //动态授权
        Role role = roleService.getById(user.getUsrRoleId());
        if (role != null) {
            Set<SysRight> rights = sysRightService.findRightByRoleId(user.getUsrRoleId());
            info.addRole(role.getRoleName()); // 添加角色
            if (rights != null && rights.size() > 0) {
                for (SysRight right : rights) {
                    info.addStringPermission(right.getRightCode()); // 添加权限
                }
            }
        }
        return info;
    }
    /**
     * 清空当前认证用户权限缓存
     */
    public void clearMyCachedAuthorizationInfo() {
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }


    /**
     * 清空所有用户权限缓存
     */
    public void clearAllCachedAuthorizationInfo() {
        if (this.isAuthorizationCachingEnabled()) { // 权限缓存是否可用
            Cache<Object, AuthorizationInfo> cache = null;
            CacheManager cacheManager = this.getCacheManager();
            if (cacheManager != null) {
                String cacheName = this.getAuthorizationCacheName(); // 获得权限缓存名称
                cache = cacheManager.getCache(cacheName); // 获得权限缓存
            }
            if (cache != null) {
                cache.clear(); // 清空
            }
        }
    }

}
